package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author 老杨
 * @version 1.0
 */
@Api(tags = "菜品管理接口")
@RestController
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    DishService dishService;

    @Autowired
    RedisTemplate redisTemplate;

    @ApiOperation(value = "菜品分页查询接口")
    @GetMapping("/page")
    public Result<PageResult> page(DishPageQueryDTO dishDTO) {
        PageResult page = dishService.page(dishDTO);
        return Result.success(page);
    }


    @ApiOperation(value = "菜品添加接口")
    @PostMapping
    public Result add(@RequestBody DishDTO dishDTO) {
        dishService.add(dishDTO);

        //添加 之后，某一分类下数据发生改变
        //清理对应 缓存的key
        String key = "dish_" + dishDTO.getCategoryId();
        clearCache(key);

        return Result.success();
    }

    @ApiOperation(value = "根据 id返回 菜品信息")
    @GetMapping("/{id}")
    public Result<DishDTO> getById(@PathVariable Long id) {
        log.info("返回的 id" + id);
        DishDTO dishDTO = dishService.getById(id);
        return Result.success(dishDTO);
    }

    @ApiOperation(value = "修改 菜品信息")
    @PutMapping
    public Result update(@RequestBody DishDTO dishDTO) {
        dishService.update(dishDTO);

        //修改菜品，如果修改了分类，则会影响多个分类下的数据
        //直接删除 dish_ 开头的 所以缓存
        clearCache("dish_*");
        return Result.success();
    }

    @ApiOperation(value = "根据id 删除菜品")
    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("删除id" + ids);
        dishService.delete(ids);
        //删除 也要 删除缓存，因为要确定 删除哪个具体分类下，还需要查询
        //不如直接 删除 缓存
        clearCache("dish_*");

        return Result.success();
    }

    @ApiOperation(value = "根据 id 禁用或启用 菜品")
    @PostMapping("/status/{status}")
    public Result openOrdisable(@PathVariable Integer status, Long id) {
        dishService.openOrdisable(status, id);

        //同理 ，不要去查询 获取到对应 的分类id，
        //直接 删除缓存
        clearCache("dish_*");
        return Result.success();
    }

    @ApiOperation(value = "根据 类别id 返回菜品集合")
    @GetMapping("/list")
    public Result<List<Dish>> list(Long categoryId) {
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    /**
     * 删除缓存
     */
    public void clearCache(String pattern) {
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

}
